package com.shwread.android.qysw;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.IBinder;
import android.widget.RemoteViews;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.netease.nim.demo.session.activity.P2PMessageActivity;
import com.netease.nimlib.sdk.NimIntent;
import com.netease.nimlib.sdk.msg.model.CustomNotification;
import com.shwread.android.qysw.activity.BubbleActivity;
import com.shwread.android.qysw10000182.R;

import java.util.List;

import logic.bean.NotiInfo;
import logic.constants.DefaultConsts;


public class PushMessageService
        extends
        Service
{
	private CustomSystemNotifyReceiver pushMessageReceiver;
	private Context                    mContext;
	
	@Override
	public void onCreate() {
		super.onCreate();
		mContext = this;
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		pushMessageReceiver = new CustomSystemNotifyReceiver();
		registerReceiver(pushMessageReceiver, new IntentFilter(mContext.getPackageName() + NimIntent.ACTION_RECEIVE_CUSTOM_NOTIFICATION));
		flags = START_STICKY;
		return super.onStartCommand(intent, flags, startId);
	}
	
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
	
	@Override
	public void onDestroy() {
		if (pushMessageReceiver != null)
		{
			unregisterReceiver(pushMessageReceiver);
			pushMessageReceiver = null;
		}
		stopForeground(true);
		Intent intent = new Intent(mContext.getPackageName() + ".push_message_destory");
		sendBroadcast(intent);
		super.onDestroy();
	}
	
	class CustomSystemNotifyReceiver
	        extends
	        BroadcastReceiver
	{
		private Context context;
		
		@Override
		public void onReceive(Context context, Intent intent) {
			this.context = context;
			String action = context.getPackageName() + NimIntent.ACTION_RECEIVE_CUSTOM_NOTIFICATION;
			if (action.equals(intent.getAction()))
			{
				CustomNotification notification = (CustomNotification) intent.getSerializableExtra(NimIntent.EXTRA_BROADCAST_MSG);
				NotiInfo info = null;
				try
				{
					Gson gson = new Gson();
					info = gson.fromJson(notification.getContent(), new TypeToken<NotiInfo>()
					{
					}.getType());
				}
				catch (Exception e)
				{
					e.printStackTrace();
					info = null;
				}
				
				if (null != info && info.getMessageId() > 0) showNotification(context, info);
				
			}
		}
		
		private void showNotification(Context context, NotiInfo msgInfo) {
			// NF2：设置Notification
			Notification mNotification = new Notification(R.drawable.ic_launcher, null, System.currentTimeMillis());
			
			// mNotification.flags |= Notification.FLAG_ONGOING_EVENT; //
			// 将此通知放到通知栏的"Ongoing"即"正在运行"组中
			mNotification.flags |= Notification.FLAG_AUTO_CANCEL; // 该通知能被状态栏的清除按钮给清除掉
			mNotification.flags |= Notification.FLAG_SHOW_LIGHTS; // 显示LED灯
			mNotification.defaults = Notification.DEFAULT_LIGHTS;
			if (true)
			{
				// 将使用默认的声音来提醒用户
				mNotification.defaults |= Notification.DEFAULT_SOUND;
			}
			if (true)
			{
				mNotification.defaults |= Notification.DEFAULT_VIBRATE;
			}
			mNotification.ledARGB = Color.BLUE;
			mNotification.ledOnMS = 5000; // 闪光时间，毫秒
			
			// NF3：加载自定义的view
			RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.noti_layout); // 创建RemoteViews
			contentView.setImageViewResource(R.id.noti_image, R.drawable.ic_launcher); // 加载图标
			contentView.setTextViewText(R.id.noti_text, msgInfo.getShortMsg()); // 设置文字
			mNotification.contentView = contentView;
			
			// NF4：显示Notification，设置通知的事件消息
			
			NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
			
			PendingIntent contentIntent = PendingIntent.getActivity(context, (int) msgInfo.getMessageId(), changeIntent(msgInfo), PendingIntent.FLAG_UPDATE_CURRENT);
			mNotification.setLatestEventInfo(context, msgInfo.getTitle(), msgInfo.getShortMsg(), contentIntent);
			//			startForeground(0x111, mNotification);
			mNotificationManager.notify((int) msgInfo.getMessageId(), mNotification);
		}
		
		Intent changeIntent(NotiInfo msgInfo) {
			Intent intent = null;
			switch (msgInfo.getPosition()) {
				case 1:// 运营平台
					intent = new Intent();
					intent.setClass(context, BubbleActivity.class);
					intent.putExtra("Running", isRunning(context));
					intent.putExtra(DefaultConsts.message_id, "" + msgInfo.getMessageId());
					intent.putExtra(DefaultConsts.message_type, msgInfo.getMsgType());
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
					break;
				case 2:// 评论
					break;
				case 3:// 电商“我的商品”最新动态
					break;
				case 4:// 客服回复消息
					break;
				default:
					break;
			}
			
			return intent;
		}
		
		/**
		 * 判断指定包名的进程是否运行
		 * 
		 * @param context
		 * @param packageName
		 *            指定包名
		 * @return 是否运行
		 */
		public boolean isRunning(Context context) {
			@SuppressWarnings ("static-access")
			ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
			List<RunningAppProcessInfo> infos = am.getRunningAppProcesses();
			for (RunningAppProcessInfo rapi : infos)
			{
				if (rapi.processName.equals(context.getPackageName())) return true;
			}
			return false;
		}
	}
}
